package com.dmcb.common.web.controller;


import com.dmcb.common.web.conversion.JsonResult;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.ModelMap;

/**
 * 基础控制类
 * <p/>
 * Created by a on 2015/3/11.
 */
public class BaseController {
    protected static final Logger log = LoggerFactory.getLogger(BaseController.class);

    /**
     * 模板页
     *
     * @param model
     * @param content
     * @return
     */
    protected String template(ModelMap model, String content) {
        model.addAttribute("content", content);
        return "template";
    }

    /**
     * 失败场景输出客户端json
     */
    public JsonResult outputJSONError(String msg) {
        JsonResult result = new JsonResult();
        result.setStatus(JsonResult.STATUS_ERROR);
        result.setMsg(msg);
        return result;
    }


    /**
     * 失败场景输出客户端json
     */
    public JsonResult outputJSONError(int status,String msg) {
        JsonResult result = new JsonResult();
        result.setStatus(status);
        result.setMsg(msg);
        return result;
    }

    /**
     * 警告场景输出json
     */
    protected JsonResult outputJSONWarn(Object obj, String msg) {
        JsonResult result = new JsonResult();
        result.setStatus(JsonResult.STATUS_WARN);
        result.setMsg(msg);
        result.setData(obj);
        return result;
    }

    /**
     * 成功场景输出客户端json
     */
    public JsonResult outputJSONSucc(Object obj) {
        JsonResult result = new JsonResult();
        result.setStatus(JsonResult.STATUS_SUCCESS);
        result.setData(obj);
        return result;
    }

    /**
     * 成功场景输出客户端json
     */
    public JsonResult outputJSONHref(String href) {
        JsonResult result = new JsonResult();
        result.setStatus(JsonResult.STATUS_SUCCESS);
        result.setHref(href);
        return result;
    }

    /**
     * 成功场景输出客户端json
     */
    public JsonResult outputJSONSucc() {
        JsonResult result = new JsonResult();
        result.setStatus(JsonResult.STATUS_SUCCESS);
        return result;
    }

    protected String transfer(String msg) {
        if (StringUtils.isNotBlank(msg)) {
            try {
                return (new ObjectMapper()).writeValueAsString(outputJSONError(msg));
            } catch (Exception e) {
                log.error("error, msg={}", msg, e);
            }
        }
        return msg;
    }

    /**
     * 成功场景输出客户端json
     */
    public JsonResult outputJSONSucc(int count,Object obj) {
        JsonResult result = new JsonResult();
        result.setStatus(JsonResult.STATUS_SUCCESS);
        result.setData(obj);
        return result;
    }
}
